<template>
    <div>
        <el-container>
            <el-main>
                <el-table :data="cart" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="商品图片">
                        <template #default="scope">
                            <img :src="scope.row.image[0].imageUrl" alt=""
                                 style="width: 50px; height: 50px">
                        </template>
                    </el-table-column>
                    <el-table-column label="商品名称" prop="product.name"></el-table-column>
                    <el-table-column label="单价">
                        <template #default="scope">
                            {{scope.row.product.salePrice.toFixed(2)}}
                        </template>
                    </el-table-column>
                    <el-table-column label="数量">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.sum"
                                             @change="value => handleChange(value,scope.row.cartId)"
                                             :min="1">
                            </el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column prop="subtotal" label="小计">
                        <template #default="scope">
                            {{ (scope.row.product.salePrice * scope.row.sum).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button @click="removeFromCart(scope.row.cartId)" type="danger" size="mini">移除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="total-price">
                    <span>总价: {{ totalPrice }}元</span>
                    <el-button type="primary" @click="checkout">去结算</el-button>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script>
export default {
    name: 'CartPage',
    data() {
        return {
            cart: [], // 购物车数据
            selectedItems: [], // 选中的商品
            totalPrice: 0, // 总价
        };
    },
    methods: {
        // 加载购物车数据
        loadCart() {
            let user = JSON.parse(sessionStorage.getItem('user'));
            this.$axios.post(`carts/listCarts/${user.id}`).then(res => {
                this.cart = res.data
                console.log(6666,this.cart)
                    // .map(item => ({ ...item, checked: false })); // 初始化时每个商品未选中
            });
        },
        // 数字输入框改变
        handleChange(value, cartId) {
            this.$axios.put(`carts/updateNum/${cartId}/${value}`)
                .then(res => {
                    // 重新计算总价
                    this.calculateTotalPrice();
                });
        },
        // 移除购物项
        removeFromCart(cartId) {
            this.$axios.delete(`carts/delete/${cartId}`)
                .then(res => {
                    if (res.data === 'yes') {
                        this.$message({
                            type: 'success',
                            message: '移除购物车项成功'
                        });
                        this.loadCart();
                    } else {
                        this.$message({
                            type: 'error',
                            message: '移除购物车项失败'
                        });
                    }
                });
        },
        // 处理选中状态变化
        handleSelectionChange(selectedItems) {
            this.selectedItems = selectedItems; // 更新选中的商品
            this.calculateTotalPrice(); // 计算总价
        },
        // 计算总价
        calculateTotalPrice() {
            this.totalPrice = this.selectedItems.reduce((total, item) => {
                return total + item.product.salePrice * item.sum;
            }, 0).toFixed(3);
        },

        // 结算
        checkout() {
            if (this.selectedItems.length === 0) {
                this.$message.warning('请选择要结算的商品');
                return;
            }
            // sessionStorage.setItem('selectedItems', JSON.stringify(this.selectedItems))
            this.$router.push({name:'Settlement',params:{selectCartSettlement:this.selectedItems}}); // 跳转到结算页面
            // console.log(333,this.selectedItems)
        },
    },
    created() {
        this.loadCart(); // 页面创建时加载购物车数据
    },
};
</script>

<style scoped>
.total-price {
    margin-top: 20px;
    text-align: right;
    font-size: 18px;
}

.total-price button {
    margin-left: 20px;
}
</style>